package rhc.common.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**缓存工具类
 * @author rhc
 *
 */
public class CacheUtil {

	/**
	 * 保存key对应value
	 */
	private static final Map<Object,Object> CACHE_KEY_VALUE=new ConcurrentHashMap<Object,Object>();
	
	/**
	 * 保存key对应过期时间
	 */
	private static final Map<Object,Long> CACHE_KEY_EXPIRETIME=new ConcurrentHashMap<Object,Long>();
	
	/**加入一个key-value
	 * @param key
	 * @param value
	 * @param existsMiliSeconds 存在的毫秒数 小于等于0则永久保存
	 */
	public static void addKey(Object key,Object value,long existsMiliSeconds){
		
		if(null == key || null == value){
			throw new NullPointerException();
		}
		
		synchronized(key){
			CACHE_KEY_VALUE.put(key, value);
			long expireTime=0;
			if(existsMiliSeconds>0){
				expireTime=System.currentTimeMillis()+existsMiliSeconds;
			}
			CACHE_KEY_EXPIRETIME.put(key, expireTime);
		}
	}
	
	/**获取一个key的value
	 * @param key
	 * @return
	 */
	public static <T> T getValue(Object key){
		if(null == key){
			throw new NullPointerException();
		}
		
		if(!CACHE_KEY_VALUE.containsKey(key)){
			return null;
		}
		
		synchronized(key){
			if(keyIsExpire(key)){
				removeKey(key);
				return null;
			}else{
				return (T) CACHE_KEY_VALUE.get(key);
			}
		}
	}
	
	/**查看一个key是否过期
	 * @param key
	 * @return
	 */
	private static boolean keyIsExpire(Object key){
		if(!CACHE_KEY_VALUE.containsKey(key)){
			return true;
		}
		
		long expireTime=CACHE_KEY_EXPIRETIME.get(key);
		
		return expireTime==0?false:(expireTime<System.currentTimeMillis()?true:false);
	}
	
	/**移除key
	 * @param key
	 */
	private static void removeKey(Object key){
		CACHE_KEY_VALUE.remove(key);
		CACHE_KEY_EXPIRETIME.remove(key);
	}
	
}
